package com.ruoyi.inducement.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.drew.imaging.ImageProcessingException;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.Threads;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.MimeTypeUtils;
import com.ruoyi.dataAnalysis.domain.InsectType;
import com.ruoyi.detection.domain.DetectionLog;

import com.ruoyi.detection.service.ModelService;

import com.ruoyi.inducement.domain.*;
import com.ruoyi.inducement.service.InducementService;
import com.ruoyi.inducement.utils.ImageInfoTool;
import com.ruoyi.inducement.utils.FileTool;


import com.ruoyi.inducement.utils.ImgDrawCircleTool;
import com.ruoyi.utils.ParseString;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * @program: base-planthopper-detection-master_202130504106_李航
 * @description:
 * @author: LiHang
 * @create: 2021-09-23 16:48
 **/
@Api("调查信息处理接口")
@ApiResponses({
        @ApiResponse(code = 200,message = "OK",response = ReturnInducementLog.class)
})

@Slf4j
@RestController
public class InducementController extends BaseController {

    @Autowired
    private InducementService inducementService;


    @Autowired
    private ModelService modelService;

    /**
     * 存储文件的路径
     */
    @Value("${ruoyi.profile}")
    private String profile;

    /**
     * 模型检测图像处理路径
     */
    @Value("${ruoyi.detectionIndecumentUrl}")
    private String detectionIndecumentUrl;

    /**
     * 向数据库插入调查信息（图片信息）
     * 保存原图，缩略图，检测图
     */
    //@ResponseBody
    @ApiOperation(value = "向数据库插入调查信息（图片信息）", notes = "示例:http://192.168.1.217:8180/insertInducementLog\n附带请求头数据\n返回识别结果")
    @PostMapping("/insertInducementLog")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "imageName",value = "上传的图片名",paramType = "query",dataType = "string"),
            @ApiImplicitParam(name = "id",value = "主键id，不用传入，会返回",paramType = "query",dataType = "string"),
            @ApiImplicitParam(name = "phone",value="登录用户手机号（不重要,可不上传）",paramType = "query",dataType = "string"),
            //@ApiImplicitParam(name = "imagePath",value="图片路径（包括图片名）",paramType = "query",dataType = "string"),
            @ApiImplicitParam(name = "diseaseType",value="病害类型",paramType = "query",dataType = "string"),
           //@ApiImplicitParam(name = "shootingTime",value="拍摄时间（自动获取，不用上传）",paramType = "query",dataType = "Date"),
            //@ApiImplicitParam(name = "uploadTime",value="上传时间（自动获取，不用上传）",paramType = "query",dataType = "Date"),
            @ApiImplicitParam(name = "weather",value="天气",paramType = "query",dataType = "string"),
            @ApiImplicitParam(name = "windpower",value="风力",paramType = "query",dataType = "string"),
            @ApiImplicitParam(name = "temperature",value="温度",paramType = "query",dataType = "string"),
            @ApiImplicitParam(name = "humidity",value="湿度",paramType = "query",dataType = "string"),
            @ApiImplicitParam(name = "province",value="调查地点 省",paramType = "query",dataType = "string"),
            @ApiImplicitParam(name = "city",value="调查地点 市",paramType = "query",dataType = "string"),
            @ApiImplicitParam(name = "district",value="调查地点 区",paramType = "query",dataType = "string"),
            @ApiImplicitParam(name = "station",value="二级站",paramType = "query",dataType = "string"),
            @ApiImplicitParam(name = "photographer",value="调查人",paramType = "query",dataType = "string"),
            @ApiImplicitParam(name = "shootingEquipment",value="拍摄设备",paramType = "query",dataType = "string"),
            //@ApiImplicitParam(name = "tag",value="自动识别的昆虫数量信息",paramType = "query",dataType = "string"),
            //@ApiImplicitParam(name = "tagManual",value="手动输入的害虫信息",paramType = "query",dataType = "string"),
            //@ApiImplicitParam(name = "originalFileName",value="原始图片名",paramType = "query",dataType = "string"),
            //@ApiImplicitParam(name = "thumPath",value="thum图片路径",paramType = "query",dataType = "string"),
            //@ApiImplicitParam(name = "resultPath",value="result图片路径",paramType = "query",dataType = "string"),

    })
    public AjaxResult insertinducement(InducementLog inducementLog, @RequestParam("imageName") MultipartFile[] files) throws IOException, ImageProcessingException, ParseException {
        List<ReturnInducementLog> result=new ArrayList<ReturnInducementLog>();
        int continueTime=0;


        for(MultipartFile file:files) {

            if (!file.isEmpty()) {

                inducementLog.setOriginalFileName(file.getOriginalFilename());
                SimpleDateFormat sdftest = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
                //String originalName=file.getOriginalFilename().split("_")[1].split("\\.")[0];
                //String shootTime=originalName.substring(0,4)+"-"+originalName.substring(4,6)+"-"+originalName.substring(6,8)+"-"+originalName.substring(8,10)+"-"+originalName.substring(10,12)+"-"+originalName.substring(12,14);
                //Date imgShootingTime =sdftest.parse(shootTime);

                String images = FileUploadUtils.upload(RuoYiConfig.getDetectionPath(), file);
                //为linux服务---------------------------
                String detectionImages = StringUtils.substringAfter(images, "profile");

                File imgFile = new File(profile + detectionImages);
                //为linux服务---------------------------
                //String detectionImages = StringUtils.substringAfter(images, "profile");
                //windows
                //File imgFile = new File(images);


                Date imgShootingTime = ImageInfoTool.ImageShootingTimeDate(imgFile);

                //String imageName = inducementLog.getDiseaseType() + "_" +
                //        sdf.format(imgShootingTime) + "_" +
                //        inducementLog.getWeather() + "_" +
                //        inducementLog.getWindpower() + "_" +
                //        inducementLog.getTemperature()+ "_" +
                //        inducementLog.getHumidity() + "_" +
                //        inducementLog.getProvince() + "_" +
                //        inducementLog.getCity() + "_" +
                //        inducementLog.getDistrict() + "_" +
                //        inducementLog.getstation() + "_" +
                //        inducementLog.getphotographer() + "_" +
                //        inducementLog.getShootingEquipment() + "__original.jpg";

                String imageName=images;
                //int flag=0;
                //List<String> AllImagePath = inducementService.selectAllImagePath();
                //for (String imagePath : AllImagePath) {
                //    if (imagePath.contains(imageName)) {
                //        flag=1;
                //        continueTime++;
                //        System.out.println(file.getOriginalFilename()+"图片已经上传过了，该图片上传失败");
                //        break;
                //    }
                //}
                //if(flag==1){
                //    continue;
                //}


                String imgCreateTime = FileTool.getImgCreateTime(imgFile);



                /* 解析识别结果构造实例存入数据库并返回, 检测不需要list集合，识别有多个可能，需要集合装载，其他的不需要 */
                List<DetectionLog> detectionLogList = new ArrayList<>();
                ImgDrawCircleTool tool = new ImgDrawCircleTool();

                try {
                    // 图片发送到Django进行识别
                    ResponseEntity<String> responseEntity = Threads.detectionRequest(profile + detectionImages, detectionIndecumentUrl);
                    log.info("responseEntity------->" + responseEntity.getBody());
                    // json格式的数据转换成数组格式
                    detectionLogList = JSON.parseArray(responseEntity.getBody(), DetectionLog.class);
                    log.info(detectionLogList.toString());
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }

                for (DetectionLog detection : detectionLogList) {
                    if (detection.getTag().length()!=2) {
                        detection.setImagePath(images).setOriginalFileName(file.getOriginalFilename()).setThumPath(images.replace("original", "thum"));
                        System.out.println(detection.getTag().length());
                        String tagNum = ParseString.getTagNum(detection.getTag());
                        log.info("检测结果：" + tagNum);
                        JSONObject jsonObject = JSON.parseObject(tagNum);
                        int num_1 = 0, num_2 = 0, num_3 = 0, num_4 = 0;
                        if (jsonObject.get("1") != null) {
                            num_1 = (int) jsonObject.get("1");
                        }
                        if (jsonObject.get("2") != null) {
                            num_2 = (int) jsonObject.get("2");
                        }
                        if (jsonObject.get("3") != null) {
                            num_3 = (int) jsonObject.get("3");
                        }
                        if (jsonObject.get("4") != null) {
                            num_4 = (int) jsonObject.get("4");
                        }
                        /*画框之后的结果图 resUrl  缩略图 已添加 */
                        List<String> tagList = JSON.parseArray(detection.getTag(), String.class);
                        //lihang的本地版本
                        //String resultPath = tool.doDrawRectangle(detection.getCorner(), tagList, images, num_1, num_2, num_3, num_4);
                        String resultPath = tool.doDrawRectangle(detection.getCorner(), tagList, profile + detectionImages, num_1, num_2, num_3, num_4).replace(profile, Constants.RESOURCE_PREFIX);

                        detection.setTag(ParseString.getTagNum(detection.getTag())).setResultPath(resultPath).setImgTime(imgCreateTime);
                        log.info(detection.toString());
                        //modelService.insertDetectionLog(detection);

                        //lihang的本地版本
                        //inducementLog.setImagePath(images);
                        //linux服务器版本
                        //全路径
                        //inducementLog.setImagePath(profile + detectionImages);
                        inducementLog.setImagePath(imageName);
                        inducementLog.setShootingTime(imgShootingTime);
                        inducementLog.setUploadTime(new Date());
                        inducementLog.setTag(detection.getTag());
                        InducementLog inducementLogReturn = inducementService.insertInducementLog(inducementLog);

                        String ImagePathOld=detection.getImagePath();
                        String path = detection.getImagePath().replace(ImagePathOld.split("/")[ImagePathOld.split("/").length-1],"");
                        String newImagePath=imageName;
                        String newthumPath=newImagePath.replace("original","thum");
                        String newResultPath=newImagePath.replace("original","original__Result");
                        detection.setImagePath(newImagePath);
                        detection.setThumPath(newthumPath);
                        detection.setResultPath(newResultPath);
                        ReturnInducementLog ReturnInducementLogs = new ReturnInducementLog();
                        ReturnInducementLogs.setPhotographer(inducementLogReturn.getPhotographer());
                        ReturnInducementLogs.setId(inducementLogReturn.getId());
                        ReturnInducementLogs.setImagePath(inducementLogReturn.getImagePath());
                        ReturnInducementLogs.setDiseaseType(inducementLogReturn.getDiseaseType());
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
                        ReturnInducementLogs.setShootingTime(sdf.format(inducementLogReturn.getShootingTime()));
                        ReturnInducementLogs.setUploadTime(sdf.format(inducementLogReturn.getUploadTime()));
                        ReturnInducementLogs.setWeather(inducementLogReturn.getWeather());
                        ReturnInducementLogs.setWindpower(inducementLogReturn.getWindpower());
                        ReturnInducementLogs.setTemperature(inducementLogReturn.getTemperature());
                        ReturnInducementLogs.setHumidity(inducementLogReturn.getHumidity());
                        ReturnInducementLogs.setProvince(inducementLogReturn.getProvince());
                        ReturnInducementLogs.setCity(inducementLogReturn.getCity());
                        ReturnInducementLogs.setDistrict(inducementLogReturn.getDistrict());
                        ReturnInducementLogs.setStation(inducementLogReturn.getStation());
                        ReturnInducementLogs.setShootingEquipment(inducementLogReturn.getShootingEquipment());
                        ReturnInducementLogs.setTag(inducementLogReturn.getTag());
                        ReturnInducementLogs.setOriginalFileName(inducementLogReturn.getOriginalFileName());
                        ReturnInducementLogs.setThumPath(inducementLogReturn.getThumPath());
                        ReturnInducementLogs.setResultPath(inducementLogReturn.getResultPath());
                        ReturnInducementLogs.setPhone(inducementLogReturn.getPhone());

                        //System.out.println(ReturnInducementLogs.toString());
                        InsectNumType insectNumType = json2InsectTypeForOne(ReturnInducementLogs.getTag());
                        ReturnInducementLogs.setInsectNumType(insectNumType);
                        ReturnInducementLogs.setAccuracy(detection.getAccuracy());
                        result.add(ReturnInducementLogs);
                    }
                    else {
                        String resultPath = tool.doDrawEmpty(profile + detectionImages).replace(profile, Constants.RESOURCE_PREFIX);
                        inducementLog.setImagePath(imageName);
                        inducementLog.setShootingTime(imgShootingTime);
                        inducementLog.setUploadTime(new Date());
                        inducementLog.setTag("{}");
                        InducementLog inducementLogReturn = inducementService.insertInducementLog(inducementLog);

                        ReturnInducementLog ReturnInducementLogs = new ReturnInducementLog();
                        ReturnInducementLogs.setPhotographer(inducementLogReturn.getPhotographer());
                        ReturnInducementLogs.setId(inducementLogReturn.getId());
                        ReturnInducementLogs.setImagePath(inducementLogReturn.getImagePath());
                        ReturnInducementLogs.setDiseaseType(inducementLogReturn.getDiseaseType());
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
                        ReturnInducementLogs.setShootingTime(sdf.format(inducementLogReturn.getShootingTime()));
                        ReturnInducementLogs.setUploadTime(sdf.format(inducementLogReturn.getUploadTime()));
                        ReturnInducementLogs.setWeather(inducementLogReturn.getWeather());
                        ReturnInducementLogs.setWindpower(inducementLogReturn.getWindpower());
                        ReturnInducementLogs.setTemperature(inducementLogReturn.getTemperature());
                        ReturnInducementLogs.setHumidity(inducementLogReturn.getHumidity());
                        ReturnInducementLogs.setProvince(inducementLogReturn.getProvince());
                        ReturnInducementLogs.setCity(inducementLogReturn.getCity());
                        ReturnInducementLogs.setDistrict(inducementLogReturn.getDistrict());
                        ReturnInducementLogs.setStation(inducementLogReturn.getStation());
                        ReturnInducementLogs.setShootingEquipment(inducementLogReturn.getShootingEquipment());
                        ReturnInducementLogs.setTag("{}");
                        ReturnInducementLogs.setOriginalFileName(inducementLogReturn.getOriginalFileName());
                        ReturnInducementLogs.setThumPath(inducementLogReturn.getThumPath());
                        ReturnInducementLogs.setResultPath(inducementLogReturn.getResultPath());
                        ReturnInducementLogs.setPhone(inducementLogReturn.getPhone());
                        //System.out.println(ReturnInducementLogs.toString());
                        //没检测结果的情况
                        InsectNumType insectNumType = json2InsectTypeForOne(ReturnInducementLogs.getTag());
                        ReturnInducementLogs.setInsectNumType(insectNumType);

                        result.add(ReturnInducementLogs);
                        //return AjaxResult.success("再试一次");
                    }

                }

            }else {
                return AjaxResult.error("上传图片异常");
            }
        }
        if(continueTime==files.length){
            return AjaxResult.success("所有图片均已被添加过");
        }
        return AjaxResult.success(result);
    }


    /**
     * 查询所有的调查信息（图片信息）
     * @return
     */
    @ApiOperation(value = "查询所有的调查信息（图片信息）", notes = "示例:http://192.168.1.217:8180/selectInducementAllInfo\n返回调查信息\n返回信息列表")
    //@ResponseBody
    @GetMapping("/selectInducementAllInfo")
    public AjaxResult selectAllInfo(){

        List<ReturnInducementLog> inducementLogs = inducementService.selectInducementLogAll();
        return AjaxResult.success(inducementLogs);
    }

    /**
     * 查询所有的调查信息（图片信息）(分页版本)
     * @return
     */
    @ApiOperation(value = "查询所有的调查信息（图片信息）(分页版本)", notes = "示例:http://192.168.1.217:8180/selectInducementAllInfoPage\n返回调查信息\n返回信息列表")
    //@ResponseBody
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum",value = "第几页",paramType = "query",dataType = "string"),
            @ApiImplicitParam(name = "pageSize",value = "一页多少数据",paramType = "query",dataType = "string")
    })
    @GetMapping("/selectInducementAllInfoPage")
    public TableDataInfo selectAllInfoPage(Integer pageNum, Integer pageSize){
        //因为在service里返回的类型会经过额外的赋值，导致不能直接调用在SendFrontController中分页的方法
        //所以是选择了使用在service中手写方法的形式来分页
        TableDataInfo tableDataInfo = inducementService.selectInducementLogAllPage(pageNum, pageSize);
        return tableDataInfo;
    }

    /**
     * 根据条件查询全部符合条件的调查信息（图片信息）
     * @return
     */
    @ApiOperation(value = "根据条件查询全部符合条件的调查信息（图片信息）", notes = "示例:http://192.168.1.217:8180/selectinducementLogByCondition\n请求头附带查询条件\n返回信息列表")
    //@ResponseBody
    @PostMapping("/selectinducementLogByCondition")
    @ApiImplicitParams({

            @ApiImplicitParam(name = "imageName",value = "上传的图片名",paramType = "query",dataType = "string"),
            @ApiImplicitParam(name = "id",value = "主键id",paramType = "query",dataType = "string"),
            @ApiImplicitParam(name = "phone",value="登录用户手机号（不重要）",paramType = "query",dataType = "string"),
            //@ApiImplicitParam(name = "imagePath",value="图片路径（包括图片名）",paramType = "query",dataType = "string"),
            @ApiImplicitParam(name = "diseaseType",value="病害类型",paramType = "query",dataType = "string"),
            @ApiImplicitParam(name = "beginTime",value="开始时间",paramType = "query",dataType = "string"),
            @ApiImplicitParam(name = "endTime",value="结束时间",paramType = "query",dataType = "string"),
            @ApiImplicitParam(name = "shootingTime",value="拍摄时间",paramType = "query",dataType = "Date"),
            @ApiImplicitParam(name = "uploadTime",value="上传时间",paramType = "query",dataType = "Date"),
            @ApiImplicitParam(name = "weather",value="天气",paramType = "query",dataType = "string"),
            @ApiImplicitParam(name = "windpower",value="风力",paramType = "query",dataType = "string"),
            @ApiImplicitParam(name = "temperature",value="温度",paramType = "query",dataType = "string"),
            @ApiImplicitParam(name = "humidity",value="湿度",paramType = "query",dataType = "string"),
            @ApiImplicitParam(name = "province",value="调查地点 省",paramType = "query",dataType = "string"),
            @ApiImplicitParam(name = "city",value="调查地点 市",paramType = "query",dataType = "string"),
            @ApiImplicitParam(name = "district",value="调查地点 区",paramType = "query",dataType = "string"),
            @ApiImplicitParam(name = "station",value="二级站",paramType = "query",dataType = "string"),
            @ApiImplicitParam(name = "photographer",value="调查人",paramType = "query",dataType = "string"),
            @ApiImplicitParam(name = "shootingEquipment",value="拍摄设备",paramType = "query",dataType = "string"),
            //@ApiImplicitParam(name = "tag",value="自动识别的昆虫数量信息",paramType = "query",dataType = "string"),
            //@ApiImplicitParam(name = "tagManual",value="手动输入的害虫信息",paramType = "query",dataType = "string"),
            //@ApiImplicitParam(name = "originalFileName",value="原始图片名",paramType = "query",dataType = "string"),
            //@ApiImplicitParam(name = "thumPath",value="thum图片路径",paramType = "query",dataType = "string"),
            //@ApiImplicitParam(name = "resultPath",value="result图片路径",paramType = "query",dataType = "string"),
            @ApiImplicitParam(name = "cdtye",value="草地贪夜蛾数量",paramType = "query",dataType = "int"),
            @ApiImplicitParam(name = "dzjym",value="稻纵卷叶螟数量",paramType = "query",dataType = "int"),
            @ApiImplicitParam(name = "ehm",value="二化螟数量",paramType = "query",dataType = "int"),
            @ApiImplicitParam(name = "dm",value="大螟数量",paramType = "query",dataType = "int"),
            @ApiImplicitParam(name = "other",value="其他害虫",paramType = "query",dataType = "int")
    })
    public AjaxResult selectinducementLogByCondition(SelectInducementLog selectInducementLog){
        List<ReturnInducementLog> inducementLogsByCondition = inducementService.selectInducementLogByCondition(selectInducementLog);
        return AjaxResult.success(inducementLogsByCondition);
    }

    /**
     * 根据条件查询全部符合条件的调查信息（图片信息）(分页)
     * @return
     */
    @ApiOperation(value = "根据条件查询全部符合条件的调查信息（图片信息）(分页)", notes = "示例:http://192.168.1.217:8180/selectinducementLogByConditionPage\n请求头附带查询条件\n返回信息列表")
    //@ResponseBody
    @PostMapping("/selectinducementLogByConditionPage")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum",value = "第几页",paramType = "query",dataType = "string"),
            @ApiImplicitParam(name = "pageSize",value = "一页多少数据",paramType = "query",dataType = "string"),
            @ApiImplicitParam(name = "imageName",value = "上传的图片名",paramType = "query",dataType = "string"),
            @ApiImplicitParam(name = "id",value = "主键id",paramType = "query",dataType = "string"),
            @ApiImplicitParam(name = "phone",value="登录用户手机号（不重要）",paramType = "query",dataType = "string"),
            //@ApiImplicitParam(name = "imagePath",value="图片路径（包括图片名）",paramType = "query",dataType = "string"),
            @ApiImplicitParam(name = "diseaseType",value="病害类型",paramType = "query",dataType = "string"),
            @ApiImplicitParam(name = "beginTime",value="开始时间",paramType = "query",dataType = "string"),
            @ApiImplicitParam(name = "endTime",value="结束时间",paramType = "query",dataType = "string"),
            @ApiImplicitParam(name = "shootingTime",value="拍摄时间",paramType = "query",dataType = "Date"),
            @ApiImplicitParam(name = "uploadTime",value="上传时间",paramType = "query",dataType = "Date"),
            @ApiImplicitParam(name = "weather",value="天气",paramType = "query",dataType = "string"),
            @ApiImplicitParam(name = "windpower",value="风力",paramType = "query",dataType = "string"),
            @ApiImplicitParam(name = "temperature",value="温度",paramType = "query",dataType = "string"),
            @ApiImplicitParam(name = "humidity",value="湿度",paramType = "query",dataType = "string"),
            @ApiImplicitParam(name = "province",value="调查地点 省",paramType = "query",dataType = "string"),
            @ApiImplicitParam(name = "city",value="调查地点 市",paramType = "query",dataType = "string"),
            @ApiImplicitParam(name = "district",value="调查地点 区",paramType = "query",dataType = "string"),
            @ApiImplicitParam(name = "station",value="二级站",paramType = "query",dataType = "string"),
            @ApiImplicitParam(name = "photographer",value="调查人",paramType = "query",dataType = "string"),
            @ApiImplicitParam(name = "shootingEquipment",value="拍摄设备",paramType = "query",dataType = "string"),
            //@ApiImplicitParam(name = "tag",value="自动识别的昆虫数量信息",paramType = "query",dataType = "string"),
            //@ApiImplicitParam(name = "tagManual",value="手动输入的害虫信息",paramType = "query",dataType = "string"),
            //@ApiImplicitParam(name = "originalFileName",value="原始图片名",paramType = "query",dataType = "string"),
            //@ApiImplicitParam(name = "thumPath",value="thum图片路径",paramType = "query",dataType = "string"),
            //@ApiImplicitParam(name = "resultPath",value="result图片路径",paramType = "query",dataType = "string"),
            @ApiImplicitParam(name = "cdtye",value="草地贪夜蛾数量",paramType = "query",dataType = "int"),
            @ApiImplicitParam(name = "dzjym",value="稻纵卷叶螟数量",paramType = "query",dataType = "int"),
            @ApiImplicitParam(name = "ehm",value="二化螟数量",paramType = "query",dataType = "int"),
            @ApiImplicitParam(name = "dm",value="大螟数量",paramType = "query",dataType = "int"),
            @ApiImplicitParam(name = "other",value="其他害虫",paramType = "query",dataType = "int")
    })
    public TableDataInfo selectinducementLogByConditionPage(SelectInducementLog selectInducementLog,Integer pageNum, Integer pageSize){

        TableDataInfo tableDataInfo = inducementService.selectInducementLogByConditionPage(selectInducementLog, pageNum, pageSize);
        return tableDataInfo;
    }

    /**
     * 根据条件查询全部符合条件的调查人姓名信息
     * @return
     */
    @ApiOperation(value = "根据条件查询全部符合条件的调查人姓名信息", notes = "示例:http://192.168.1.217:8180/selectphotographerByCondition\n请求头附带查询条件\n返回信息列表")
    //@ResponseBody
    @PostMapping("/selectphotographerByCondition")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "imageName",value = "上传的图片名",paramType = "query",dataType = "string"),
            @ApiImplicitParam(name = "id",value = "主键id",paramType = "query",dataType = "string"),
            @ApiImplicitParam(name = "phone",value="登录用户手机号（不重要）",paramType = "query",dataType = "string"),
            //@ApiImplicitParam(name = "imagePath",value="图片路径（包括图片名）",paramType = "query",dataType = "string"),
            @ApiImplicitParam(name = "diseaseType",value="病害类型",paramType = "query",dataType = "string"),
            @ApiImplicitParam(name = "beginTime",value="开始时间",paramType = "query",dataType = "string"),
            @ApiImplicitParam(name = "endTime",value="结束时间",paramType = "query",dataType = "string"),
            @ApiImplicitParam(name = "shootingTime",value="拍摄时间",paramType = "query",dataType = "Date"),
            @ApiImplicitParam(name = "uploadTime",value="上传时间",paramType = "query",dataType = "Date"),
            @ApiImplicitParam(name = "weather",value="天气",paramType = "query",dataType = "string"),
            @ApiImplicitParam(name = "windpower",value="风力",paramType = "query",dataType = "string"),
            @ApiImplicitParam(name = "temperature",value="温度",paramType = "query",dataType = "string"),
            @ApiImplicitParam(name = "humidity",value="湿度",paramType = "query",dataType = "string"),
            @ApiImplicitParam(name = "province",value="调查地点 省",paramType = "query",dataType = "string"),
            @ApiImplicitParam(name = "city",value="调查地点 市",paramType = "query",dataType = "string"),
            @ApiImplicitParam(name = "district",value="调查地点 区",paramType = "query",dataType = "string"),
            @ApiImplicitParam(name = "station",value="二级站",paramType = "query",dataType = "string"),
            @ApiImplicitParam(name = "photographer",value="调查人",paramType = "query",dataType = "string"),
            @ApiImplicitParam(name = "shootingEquipment",value="拍摄设备",paramType = "query",dataType = "string"),
            //@ApiImplicitParam(name = "tag",value="自动识别的昆虫数量信息",paramType = "query",dataType = "string"),
            //@ApiImplicitParam(name = "tagManual",value="手动输入的害虫信息",paramType = "query",dataType = "string"),
            //@ApiImplicitParam(name = "originalFileName",value="原始图片名",paramType = "query",dataType = "string"),
            //@ApiImplicitParam(name = "thumPath",value="thum图片路径",paramType = "query",dataType = "string"),
            //@ApiImplicitParam(name = "resultPath",value="result图片路径",paramType = "query",dataType = "string"),
            @ApiImplicitParam(name = "cdtye",value="草地贪夜蛾数量",paramType = "query",dataType = "int"),
            @ApiImplicitParam(name = "dzjym",value="稻纵卷叶螟数量",paramType = "query",dataType = "int"),
            @ApiImplicitParam(name = "ehm",value="二化螟数量",paramType = "query",dataType = "int"),
            @ApiImplicitParam(name = "dm",value="大螟数量",paramType = "query",dataType = "int"),
            @ApiImplicitParam(name = "other",value="其他害虫",paramType = "query",dataType = "int")
    })
    public AjaxResult selectphotographerByCondition(SelectInducementLog selectInducementLog){
        List<String> photographers = inducementService.selectphotographerByCondition(selectInducementLog);
        return AjaxResult.success(photographers);
    }

    /**
     * 根据条件查询调查播报信息（图片信息）
     * @return 返回播报信息，用于展示折线图
     */
    @ApiOperation(value = "根据条件查询调查信息（图片信息）", notes = "示例:http://192.168.1.217:8180/selectInducementTagByCondition\n请求头附带查询条件\n返回播报信息，用于展示折线图")
    //@ResponseBody
    @PostMapping("/selectInducementTagByCondition")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "imageName",value = "上传的图片名",paramType = "query",dataType = "string"),
            @ApiImplicitParam(name = "id",value = "主键id",paramType = "query",dataType = "string"),
            @ApiImplicitParam(name = "phone",value="登录用户手机号（不重要）",paramType = "query",dataType = "string"),
            //@ApiImplicitParam(name = "imagePath",value="图片路径（包括图片名）",paramType = "query",dataType = "string"),
            @ApiImplicitParam(name = "diseaseType",value="病害类型",paramType = "query",dataType = "string"),
            @ApiImplicitParam(name = "beginTime",value="开始时间",paramType = "query",dataType = "string"),
            @ApiImplicitParam(name = "endTime",value="结束时间",paramType = "query",dataType = "string"),
            @ApiImplicitParam(name = "shootingTime",value="拍摄时间",paramType = "query",dataType = "Date"),
            @ApiImplicitParam(name = "uploadTime",value="上传时间",paramType = "query",dataType = "Date"),
            @ApiImplicitParam(name = "weather",value="天气",paramType = "query",dataType = "string"),
            @ApiImplicitParam(name = "windpower",value="风力",paramType = "query",dataType = "string"),
            @ApiImplicitParam(name = "temperature",value="温度",paramType = "query",dataType = "string"),
            @ApiImplicitParam(name = "humidity",value="湿度",paramType = "query",dataType = "string"),
            @ApiImplicitParam(name = "province",value="调查地点 省",paramType = "query",dataType = "string"),
            @ApiImplicitParam(name = "city",value="调查地点 市",paramType = "query",dataType = "string"),
            @ApiImplicitParam(name = "district",value="调查地点 区",paramType = "query",dataType = "string"),
            @ApiImplicitParam(name = "station",value="二级站",paramType = "query",dataType = "string"),
            @ApiImplicitParam(name = "photographer",value="调查人",paramType = "query",dataType = "string"),
            @ApiImplicitParam(name = "shootingEquipment",value="拍摄设备",paramType = "query",dataType = "string"),
            //@ApiImplicitParam(name = "tag",value="自动识别的昆虫数量信息",paramType = "query",dataType = "string"),
            //@ApiImplicitParam(name = "tagManual",value="手动输入的害虫信息",paramType = "query",dataType = "string"),
            //@ApiImplicitParam(name = "originalFileName",value="原始图片名",paramType = "query",dataType = "string"),
            //@ApiImplicitParam(name = "thumPath",value="thum图片路径",paramType = "query",dataType = "string"),
            //@ApiImplicitParam(name = "resultPath",value="result图片路径",paramType = "query",dataType = "string"),
            @ApiImplicitParam(name = "cdtye",value="草地贪夜蛾数量",paramType = "query",dataType = "int"),
            @ApiImplicitParam(name = "dzjym",value="稻纵卷叶螟数量",paramType = "query",dataType = "int"),
            @ApiImplicitParam(name = "ehm",value="二化螟数量",paramType = "query",dataType = "int"),
            @ApiImplicitParam(name = "dm",value="大螟数量",paramType = "query",dataType = "int"),
            @ApiImplicitParam(name = "other",value="其他害虫",paramType = "query",dataType = "int")
    })
    public AjaxResult selectTagByCondition(SelectInducementLog selectInducementLog) throws ParseException {
        List<BroadcastInfo> broadcastInfo = inducementService.getBroadcastInfo(selectInducementLog);
        return AjaxResult.success(broadcastInfo);
    }



    /**
     * 根据条件查询昆虫信息（图片信息），主要用于查询7天内，或者30日天内或者N天内这种数据
     * days 就是提前几天
     * @return 返回播报信息，用于展示折线图
     */
    @ApiOperation(value = "根据条件查询调查信息（图片信息）,主要用于查询7天内，或者30日天内或者N天内这种数据", notes = "示例:http://192.168.1.217:8180/selectInducementTagBeforeNdays\n请求头附带查询条件以及提前的天数\n返回播报信息，用于展示折线图")
    //@ResponseBody
    @PostMapping("/selectInducementTagBeforeNdays")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "imageName",value = "上传的图片名",paramType = "query",dataType = "string"),
            @ApiImplicitParam(name = "id",value = "主键id",paramType = "query",dataType = "string"),
            @ApiImplicitParam(name = "phone",value="登录用户手机号（不重要）",paramType = "query",dataType = "string"),
            //@ApiImplicitParam(name = "imagePath",value="图片路径（包括图片名）",paramType = "query",dataType = "string"),
            @ApiImplicitParam(name = "diseaseType",value="病害类型",paramType = "query",dataType = "string"),
            @ApiImplicitParam(name = "beginTime",value="开始时间",paramType = "query",dataType = "string"),
            @ApiImplicitParam(name = "endTime",value="结束时间",paramType = "query",dataType = "string"),
            @ApiImplicitParam(name = "shootingTime",value="拍摄时间",paramType = "query",dataType = "Date"),
            @ApiImplicitParam(name = "uploadTime",value="上传时间",paramType = "query",dataType = "Date"),
            @ApiImplicitParam(name = "weather",value="天气",paramType = "query",dataType = "string"),
            @ApiImplicitParam(name = "windpower",value="风力",paramType = "query",dataType = "string"),
            @ApiImplicitParam(name = "temperature",value="温度",paramType = "query",dataType = "string"),
            @ApiImplicitParam(name = "humidity",value="湿度",paramType = "query",dataType = "string"),
            @ApiImplicitParam(name = "province",value="调查地点 省",paramType = "query",dataType = "string"),
            @ApiImplicitParam(name = "city",value="调查地点 市",paramType = "query",dataType = "string"),
            @ApiImplicitParam(name = "district",value="调查地点 区",paramType = "query",dataType = "string"),
            @ApiImplicitParam(name = "station",value="二级站",paramType = "query",dataType = "string"),
            @ApiImplicitParam(name = "photographer",value="调查人",paramType = "query",dataType = "string"),
            @ApiImplicitParam(name = "shootingEquipment",value="拍摄设备",paramType = "query",dataType = "string"),
            //@ApiImplicitParam(name = "tag",value="自动识别的昆虫数量信息",paramType = "query",dataType = "string"),
            //@ApiImplicitParam(name = "tagManual",value="手动输入的害虫信息",paramType = "query",dataType = "string"),
            //@ApiImplicitParam(name = "originalFileName",value="原始图片名",paramType = "query",dataType = "string"),
            //@ApiImplicitParam(name = "thumPath",value="thum图片路径",paramType = "query",dataType = "string"),
            //@ApiImplicitParam(name = "resultPath",value="result图片路径",paramType = "query",dataType = "string"),

            @ApiImplicitParam(name = "cdtye",value="草地贪夜蛾数量",paramType = "query",dataType = "int"),
            @ApiImplicitParam(name = "dzjym",value="稻纵卷叶螟数量",paramType = "query",dataType = "int"),
            @ApiImplicitParam(name = "ehm",value="二化螟数量",paramType = "query",dataType = "int"),
            @ApiImplicitParam(name = "dm",value="大螟数量",paramType = "query",dataType = "int"),
            @ApiImplicitParam(name = "other",value="其他害虫",paramType = "query",dataType = "int"),

            @ApiImplicitParam(name = "days",value="最近几天的这个几",paramType = "query",dataType = "int")
    })
    public AjaxResult selectTagBeforeNdays(SelectInducementLog selectInducementLog, int days) throws ParseException {
        Calendar now =Calendar.getInstance();
        Date date = new Date();
        now.setTime(date);

        now.set(Calendar.DATE,now.get(Calendar.DATE)-days);

        selectInducementLog.setBeginTime(now.getTime());
        selectInducementLog.setEndTime(date);
        List<BroadcastInfo> broadcastInfo = inducementService.getBroadcastInfo(selectInducementLog);
        return AjaxResult.success(broadcastInfo);
    }

    /**
     * 记录手动记录的害虫数量
     *
     * @return 返回播报信息，用于展示折线图
     */
    @ApiOperation(value = "添加手动记录的害虫数量", notes = "示例:http://192.168.1.217:8180/updateInducementManualTag\n请求头附带查询条件以及提前的天数\n返回播报信息，用于展示折线图")
    //@ResponseBody
    @PostMapping("/updateInducementManualTag")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id",value="对应的数据id",paramType = "query",dataType = "int"),
            @ApiImplicitParam(name = "cdtye",value="草地贪夜蛾数量",paramType = "query",dataType = "int"),
            @ApiImplicitParam(name = "dzjym",value="稻纵卷叶螟数量",paramType = "query",dataType = "int"),
            @ApiImplicitParam(name = "ehm",value="二化螟数量",paramType = "query",dataType = "int"),
            @ApiImplicitParam(name = "dm",value="大螟数量",paramType = "query",dataType = "int"),
            @ApiImplicitParam(name = "other",value="其他害虫",paramType = "query",dataType = "int")

    })
    public AjaxResult updateManualTag(InsectNumType insectNumType,@RequestParam("id") int id) throws ParseException {
        SelectInducementLog selectinducementLog = new SelectInducementLog();
        selectinducementLog.setDm(insectNumType.getDm());
        selectinducementLog.setCdtye(insectNumType.getCdtye());
        selectinducementLog.setDzjym(insectNumType.getDzjym());
        selectinducementLog.setEhm(insectNumType.getEhm());
        selectinducementLog.setOther(insectNumType.getOther());
        selectinducementLog.setId(id);
        int i = inducementService.updateManualTag(selectinducementLog);

        return AjaxResult.success(i);
    }



    //@RequestMapping("/test")
    //public void test(@RequestParam("imageName") MultipartFile file) throws IOException {
    //    String images = FileUploadUtils.upload(RuoYiConfig.getDetectionPath(), file);
    //    System.out.println(images);
    //}

    /**
     * 获取文件名的后缀
     *
     * @param file 表单文件
     * @return 后缀名
     */
    public static final String getExtension(MultipartFile file)
    {
        String extension = FilenameUtils.getExtension(file.getOriginalFilename());
        if (StringUtils.isEmpty(extension))
        {
            extension = MimeTypeUtils.getExtension(file.getContentType());
        }
        return extension;
    }
    /**
     * 将数据库中的JSON格式转换为对象格式
     * other : 0,
     * 'dm': 1,
     * 'ehm': 2,
     * 'dzjym': 3,
     * 'cdtye': 4,
     *
     * @param tag tag
     * @return InsectType类型
     */
    public static InsectNumType json2InsectTypeForOne(String tag) {

        int dm=0;

        int ehm = 0;

        int dzjym = 0;

        int cdtye = 0;

        int other = 0;

        //System.out.println(tag);
        JSONObject totalNum = JSON.parseObject(tag);
        if (totalNum.containsKey("1")) {
            dm += (Integer) totalNum.get("1");
        }
        if (totalNum.containsKey("2")) {
            ehm += (Integer) totalNum.get("2");
        }
        if (totalNum.containsKey("3")) {
            dzjym += (Integer) totalNum.get("3");
        }
        if (totalNum.containsKey("4")) {
            cdtye += (Integer) totalNum.get("4");
        }

        if (totalNum.containsKey("0")) {
            other += (Integer) totalNum.get("0");
        }

        return new InsectNumType(dm,ehm,dzjym,cdtye, other);
    }

}
